package com.netty.server.base;

import com.netty.server.sender.CmdRequest;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOutboundInvoker;

import java.util.Optional;

/**
 * @author: 王霄
 * @date: 2022/1/19 16:10
 **/
public class DefaultConnection implements Connection {

    private final Channel channel;
    private final String mac;

    public DefaultConnection(Channel channel) {
        this.channel = channel;
        this.mac = channel.attr(ConnectionAttr.MAC).get();
    }

    @Override
    public String getId() {
        return mac;
    }

    @Override
    public ConnectStatus getStatus() {
        return channel.attr(ConnectionAttr.STATUS).get();
    }

    @Override
    public void disconnect() {
        Optional.ofNullable(channel).ifPresent(ChannelOutboundInvoker::close);
    }

    @Override
    public void send(CmdRequest request) {
        if (getStatus() == ConnectStatus.ACTIVE) {
            channel.writeAndFlush(request);
        }
    }
}
